package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Cart;
import com.scau.yangsuiyu.estore.dababases.entity.Item;
import com.scau.yangsuiyu.estore.dababases.entity.Orders;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

/**
 * @author suiyu_yang
 * @description 购物车Cart的Dao
 * @date 2019-06-21 15:01
 * @email suiyu_yang@163.com
 */
public class CartDao {
    public void insert(Cart cart) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(cart);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(Cart cart) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(cart);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void update(Cart cart) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(cart);

        session.flush();
        transaction.commit();
        HibernateUtil.closeSession();
    }

    public List<Cart> getCartByBuyer(Buyer buyer) {
        Session session = HibernateUtil.currentSession();

        String sql = "select * from cart  where cart.buyer_id = " + buyer.getId();

        //通过addEntity()方法来实现。addEntity()方法可以讲结果转换为实体
        List<Cart> cartsList = session.createSQLQuery(sql).addEntity(Cart.class).list();
        HibernateUtil.closeSession();

        return cartsList;
    }


}
